class ListNode3 {
    int val;
    ListNode3 next;
    ListNode3 head;

    ListNode3() {
    }

    ListNode3(int val) {
        this.val = val;
    }

    ListNode3(int val, ListNode3 next) {
        this.val = val;
        this.next = next;
    }
}

public class Java1017 {
    public int size(ListNode3 head){
        ListNode3 x = head;
        int count = 0;
        while (x != null){
            count++;
            x = x.next;
        }
        return count;
    }

    //返回倒数第k个结点的val值
    public int kthToLast(int k,ListNode3 head){
        if(k < 0 || k > size(head)){
            return -1;
        }

        int count = 0;
        ListNode3 fast = head;
        ListNode3 slow = head;
        while (count != k-1){
            //代替k如果大于size的写法
//           if(fast == null){
//                return -1;
//            }
            fast = fast.next;
            count++;
        }
        while (fast.next != null){
            fast = fast.next;
            slow = slow.next;
        }
        return slow.val;

    }

    public static void main(String[] args) {
        ListNode3 x1 = new ListNode3(12);
        ListNode3 x2 = new ListNode3(23);
        ListNode3 x3 = new ListNode3(34);
        ListNode3 x4 = new ListNode3(45);
        ListNode3 x5 = new ListNode3(56);

        x1.next = x2;
        x2.next = x3;
        x3.next = x4;
        x4.next = x5;

        ListNode3 head = x1;

        Java1017 y = new Java1017();
        System.out.println(y.kthToLast(5,x1));

    }
}
